package org.c797797ty.railway.service;
import org.c797797ty.railway.model.User;
import org.c797797ty.railway.util.DBUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author C797797ty
 * @data 2025/11/4 10:57
 */
public class MessageService {
    /**
     * 消息服务类 - 处理系统消息的发送和查询
     */     private static Scanner scanner = new Scanner(System.in);

        /**
         * 发送系统消息给指定用户
         */
        public static void sendSystemMessage(int userId, String messageContent) {
            try {
                // 确保消息内容不为空且长度合理
                if (messageContent == null || messageContent.trim().isEmpty()) {
                    System.err.println("消息内容不能为空");
                    return;
                }

                // 截断过长的消息（避免数据库字段长度限制）
                if (messageContent.length() > 490) {
                    messageContent = messageContent.substring(0, 490) + "...";
                }

                DBUtil.executeUpdate(
                        "INSERT INTO system_messages (user_id, message_content) VALUES (?, ?)",
                        userId, messageContent
                );
                System.out.println("系统消息发送成功");
            } catch (SQLException e) {
                System.err.println("发送系统消息失败: " + e.getMessage());
                // 提供更详细的错误信息
                if (e.getMessage().contains("Incorrect string value")) {
                    System.err.println("提示：数据库字符集可能不支持中文，请执行字符集修改SQL");
                }
            }
        }

        /**
         * 查看当前登录用户的系统消息
         */
        public static void viewSystemMessages(User user) {
            if (user == null) {
                System.out.println("请先登录！");
                return;
            }

            try (ResultSet rs = DBUtil.executeQuery(
                    "SELECT * FROM system_messages WHERE user_id = ? ORDER BY created_at DESC",
                    user.getId())) {

                System.out.println("\n===== 系统消息 =====");
                boolean hasMessages = false;
                while (rs.next()) {
                    hasMessages = true;
                    String readStatus = rs.getBoolean("is_read") ? "[已读]" : "[未读]";
                    System.out.printf("%s %s | %s\n",
                            readStatus,
                            rs.getString("message_content"),
                            rs.getTimestamp("created_at"));
                }

                if (!hasMessages) {
                    System.out.println("暂无系统消息");
                } else {
                    // 标记消息为已读
                    markMessagesAsRead(user.getId());
                }
            } catch (SQLException e) {
                System.err.println("查询系统消息失败: " + e.getMessage());
            }
        }

        /**
         * 标记用户的所有消息为已读
         */
        private static void markMessagesAsRead(int userId) {
            try {
                DBUtil.executeUpdate(
                        "UPDATE system_messages SET is_read = TRUE WHERE user_id = ? AND is_read = FALSE",
                        userId
                );
            } catch (SQLException e) {
                System.err.println("标记消息为已读失败: " + e.getMessage());
            }
        }

        /**
         * 获取指定用户的未读消息数量
         */
        public static int getUnreadMessageCount(int userId) {
            try (ResultSet rs = DBUtil.executeQuery(
                    "SELECT COUNT(*) as count FROM system_messages WHERE user_id = ? AND is_read = FALSE",
                    userId)) {

                if (rs.next()) {
                    return rs.getInt("count");
                }
            } catch (SQLException e) {
                System.err.println("获取未读消息数量失败: " + e.getMessage());
            }
            return 0;
        }
}
